package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Organization;
import com.tianxin.workbao.workBao.bean.OrganizationDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.BeansUtil;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/6/18.
 */

public class OrganizationDataProvide extends BaseDataProvide {

    private List<Organization> organizations;
    private UpdateListViewListener mUpdateListViewListener;
    private int mPage = 1;
    private OrganizationDao organizationDao;

    public OrganizationDataProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mContext = context;
        this.mUpdateListViewListener = listener;
        organizationDao = mGreenDaoHelper.getDaoSession().getOrganizationDao();
    }

    public void getOrganizations() {
        organizationsfromDB();
        if (organizations.isEmpty()) {
            getOrganizationFromServer();
        }
        refreshUI();
    }


    /**
     * 从数据库中 获取所的组织机枸
     */
    private void organizationsfromDB() {
        OrganizationDao organizationDao = mGreenDaoHelper.getDaoSession().getOrganizationDao();
        Query query = organizationDao.queryBuilder()
                .where(OrganizationDao.Properties.Isis.eq(1))
                .where(OrganizationDao.Properties.Pid.notEq(0)).orderAsc(OrganizationDao.Properties.Id)
                .build();
        this.organizations = query.list();
    }

    /**
     * 从服务器上 获取所的组织机枸
     */
    private void getOrganizationFromServer() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        } else {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            RequestParams params = new RequestParams(map);
            CommonOkHttpClient.get(CommonRequest.createGetRequest(URL.getOrganizationUrl(), params), getDisposeDataHandle());
        }
    }

    public DisposeDataHandle getDisposeDataHandle() {
        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener(), Organization.class);
        }
        return disposeDataHandle;
    }

    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                public void onSuccess(Object responseObj) {
                    mUpdateListViewListener.hideProgress();
                    try {
                        JSONObject object = new JSONObject(responseObj.toString());
                        int status = object.getInt(Constant.RESPONSE_STATUS);
                        String information = object.getString(Constant.RESPONSE_INFO);
                        if (status > 0) {
                            String dataJson = object.getString(Constant.RESPONSE_DATA);
                            if (dataJson != null || dataJson.length() > 2) {
                                try {
                                    if (dataJson.startsWith("[") && dataJson.endsWith("]") && dataJson.length() > 3) {
                                        if (organizations != null && !organizations.isEmpty()) {
                                            organizations.clear();
                                        }
                                        organizations = BeansUtil.organizationToBeans(dataJson);
                                        refreshUI();
                                        saveToDb(organizations);
                                    }

                                } catch (Exception e) {
                                    mUpdateListViewListener.showMessage("organization To Bean Error :类型转换出错" + e.getMessage());
                                }
                            } else {
                                mUpdateListViewListener.showMessage(information);
                            }
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }

                    } catch (JSONException e) {
                        showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                        e.printStackTrace();
                    }
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mUpdateListViewListener.hideProgress();
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    @Override
    public void refreshUI() {

        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(organizations);
        } else {
            mUpdateListViewListener.onRefreshData(organizations);
        }

    }

    private void saveToDb(Object obj) {
        if (obj instanceof List) {
            for (int i = 0; i < organizations.size(); i++) {
                organizationDao.insertOrReplace(organizations.get(i));
            }
        } else {
            organizationDao.insertOrReplace((Organization) obj);
        }
    }
}
